﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace MD5Sum
{
    /**
     * 
     * 
     */
    public partial class AppForm : Form
    {
        private string dir = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
        private string filePath;
        private string md5;
        private string md5Hash;
        //private KeyValuePair<string, bool> result;

        HashGenerator hashGenerator = new HashGenerator();
        List<CompareItem> data;

        DataTable dtGen = new DataTable();
        DataTable dtResult = new DataTable();
        List<CompareItem> result;
        int status = 1;

        public static readonly string md5File = "md5sum";


        public AppForm()
        {
            InitializeComponent();
        }



        private void AppFormShown(object sender, EventArgs e)
        {
            //初始化DataTable，并将datatable绑定到DataGridView的数据源
            DataColumn c1 = new DataColumn("File", typeof(string));
            DataColumn c2 = new DataColumn("MD5", typeof(string));

            dtGen.Columns.Add(c1);
            dtGen.Columns.Add(c2);
            gridGen.DataSource = dtGen.DefaultView;
            gridGen.Columns[0].Width = 200;
            gridGen.Columns[1].Width = 220;
            gridGen.ReadOnly = true;
            gridGen.AllowUserToAddRows = false;
            gridGen.RowHeadersVisible = false;

            DataColumn c3 = new DataColumn("File", typeof(string));
            DataColumn c4 = new DataColumn("MD5", typeof(string));
            DataColumn c5 = new DataColumn("Matched", typeof(string));

            dtResult.Columns.Add(c3);
            dtResult.Columns.Add(c5);
            dtResult.Columns.Add(c4);
            gdResult.DataSource = dtResult.DefaultView;
            gdResult.Columns[0].Width = 150;
            gdResult.Columns[1].Width = 60;
            gdResult.Columns[2].Width = 210;
            gdResult.ReadOnly = true;
            gdResult.AllowUserToAddRows = false;
            gdResult.RowHeadersVisible = false;



            pnlRunning.BringToFront();
            pnlRunning.Visible = true;

            btnCheck.Enabled = false;

            pnlGen.Visible = false;
            pnlVerify.Visible = false;
            pnlRunning.Visible = true;
            pnlGen.Location = new Point(0, 0);
            pnlRunning.Location = new Point(0, 0);
            this.Size = new Size(475, 228);

            backgroundWorker1.DoWork += automaticRun;
            backgroundWorker1.RunWorkerCompleted += updateUI;
            backgroundWorker1.RunWorkerAsync();
        }

        private void automaticRun(object sender, DoWorkEventArgs e)
        {
            if (File.Exists(md5File))
            {
                result = hashGenerator.compare();
                status = 1;
            }
            else
            {
                generate();
                status = -1;
            }
        }

        private void updateUI(object sender, RunWorkerCompletedEventArgs e)
        {
            pnlRunning.Visible = false;
            btnCheck.Enabled = true;
            if (status == 1)
            {
                if (result == null)
                {

                    lblMessage.Text = "没有数据文件(md5sum)!";
                    pnlVerify.Visible = true;
                }
                else
                {
                    pnlVerify.Visible = true;
                    dtResult.Clear();
                    foreach (CompareItem item in result)
                    {
                        dtResult.Rows.Add(item.FileName, item.IsMatched, item.IsMatched.Equals("Yes") ? item.RightHash : (item.RightHash + "\n" + item.WrongHash));
                    }
                }
            }
            else
            {
                pnlGen.Visible = true;
                dtGen.Clear();
                foreach (CompareItem item in data)
                {
                    dtGen.Rows.Add(item.FileName, item.RightHash);
                }
                gridGen.DataSource = dtGen;

                List<String> fileContent = new List<String>();
                foreach (CompareItem item in data)
                {
                    fileContent.Add(item.RightHash + "\t*" + item.FileName);
                }
                if (fileContent.Count == 0)
                {
                    return;
                }
                File.WriteAllLines("md5sum", fileContent);
                btnReload.Enabled = true;
            }
        }

        private void generate()
        {
            if (File.Exists("md5sum"))
            {
                DialogResult dr = MessageBox.Show("数据已存在, 覆盖?", "确认", MessageBoxButtons.OKCancel);
                if (dr == DialogResult.Cancel)
                {
                    return;
                }
            }
            data = hashGenerator.generate();

        }


        private void btnCheck_Click(object sender, EventArgs e)
        {
            status = 1;
            pnlRunning.Visible = true;
            btnCheck.Enabled = false;
            lblMessage.Text = "Please wait...";
            backgroundWorker1.RunWorkerAsync();
        }

        private void gdResult_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                e.CellStyle.Font = new Font("Consolas", 12);
                e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                if (e.Value.ToString() == "Yes")
                {
                    e.CellStyle.BackColor = Color.Green;
                    e.Value = "√";
                }

                else
                {
                    e.CellStyle.BackColor = Color.Red;
                    e.Value = "×";
                }
            }
        }

        private void btnReload_Click(object sender, EventArgs e)
        {
            if (File.Exists(md5File))
            {
                status = 1;
            }
            else
            {
                status = -1;
            }
            pnlGen.Visible = false;
            pnlVerify.Visible = false;
            pnlRunning.Visible = true;
            backgroundWorker1.RunWorkerAsync();

        }
    }
}
